﻿using System;
using System.Data;
using System.Drawing;
using System.Web.UI.WebControls;

using HsTec.Mobile.Green.BLL;
using System.Drawing.Imaging;
using HsTec.Mobile.Green.Util;
using Baimasoft.Manage.SqlServerDAL;

public partial class ReportAnalysis_ComparativeAnalysis : System.Web.UI.Page
{
    ReportAnalysisBLL bll = new ReportAnalysisBLL();
    Param MyP = new Param();
    private string sArea = String.Empty;
    private string sCheck = String.Empty;

    protected void Page_Load(object sender, EventArgs e)
    {
        if ((string)Session["Baimasoft_Pers_ID"] == null)
        {
            Response.Redirect("../Logon.aspx");
        }
        if (!this.IsPostBack)
        {
            //绑定区域下拉框
            lstArea.Attributes.Add("onclick", "FindSelectedItems(this," + txtArea.ClientID + ");SetHiddenArea();");
            this.BindlstArea();
            tblType.Attributes.Add("onclick", "ChangeBrl();");
            try
            {
                Indicator.Text = Request.QueryString["sIndicator"].ToString();
            }
            catch
            {

            }
            GridView1.Attributes.Add("BorderColor", "LightSkyBlue");
            if (ViewState["sortDirection"] == null)
            {
                ViewState["sortDirection"] = " ASC";
            }
            if (ViewState["sortExpression"] == null)
            {
                ViewState["sortExpression"] = String.Empty;
            }
            this.BindtvYears();
            this.BindddlLargeArea();
            this.BindddlEquipment1();
            this.BindddlEquipment2();
            this.BindddlEquipment3();
            this.BindddlArea();
            this.BindtYears();
        }
    }

    private void BindtYears()
    {
        ddlYears.DataTextField = "Name";
        ddlYears.DataValueField = "Name";
        ddlYears.DataSource = MyP.GetCodeByParentCode("1");
        ddlYears.DataBind();
        ddlYears.Items.Insert(0, "请选择...");
        ddlYears.Items[0].Value = "";
    }

    private void BindddlArea()
    {
        ddlArea.DataSource = bll.GetAreaALL();
        ddlArea.DataTextField = "Name";
        ddlArea.DataValueField = "ID";
        ddlArea.DataBind();
    }

    private void BindddlEquipment3()
    {
        ddlEquipment3.DataTextField = "Name";
        ddlEquipment3.DataValueField = "Code";
        ddlEquipment3.DataSource = MyP.GetCodeByParentCode("4");
        ddlEquipment3.DataBind();
        ddlEquipment3.Items.Insert(0, "请选择...");
        ddlEquipment3.Items[0].Value = "";
    }

    private void BindddlEquipment2()
    {
        ddlEquipment2.DataTextField = "Name";
        ddlEquipment2.DataValueField = "Code";
        ddlEquipment2.DataSource = MyP.GetCodeByParentCode("4");
        ddlEquipment2.DataBind();
        ddlEquipment2.Items.Insert(0, "请选择...");
        ddlEquipment2.Items[0].Value = "";
    }

    private void BindddlEquipment1()
    {
        ddlEquipment1.DataTextField = "Name";
        ddlEquipment1.DataValueField = "Code";
        ddlEquipment1.DataSource = MyP.GetCodeByParentCode("4");
        ddlEquipment1.DataBind();
        ddlEquipment1.Items.Insert(0, "请选择...");
        ddlEquipment1.Items[0].Value = "";
    }

    private void BindddlLargeArea()
    {
        ddlLargeArea.DataTextField = "Name";
        ddlLargeArea.DataValueField = "Code";
        ddlLargeArea.DataSource = MyP.GetCodeByParentCode("3");
        ddlLargeArea.DataBind();
        ddlLargeArea.Items.Insert(0, "请选择...");
        ddlLargeArea.Items[0].Value = "";
    }

    /// <summary>
    /// 绑定时间树
    /// </summary>
    private void BindtvYears()
    {
        bll.BindTreeView(tvYears);
    }

    /// <summary>
    /// 绑定区域数据
    /// </summary>
    private void BindlstArea()
    {
        lstArea.DataSource = bll.GetAreaALL();
        lstArea.DataTextField = "Name";
        lstArea.DataValueField = "ID";
        lstArea.DataBind();
    }

    /// <summary>
    /// --------------------------------需要改进-------------------------------
    /// </summary>
    private void BindGridViewData()
    {
        string sItems = String.Empty;
        if (tblType.SelectedValue == "1")
        {
            switch (rblIndicators.SelectedValue)
            {
                case "1":
                    sItems = "Powers as [总电量(度)]";
                    break;
                case "2":
                    sItems = "cast(ManagementRoom*100 as decimal(10,2)) as 管理用房耗电,cast(IntegratedRoom*100 as decimal(10,2)) as 综合机房耗电,cast(BusinessOffice*100 as decimal(10,2)) as 营业厅耗电,cast(BaseStation*100 as decimal(10,2)) as 基站耗电";
                    break;
                case "3":
                    sItems = "cast(UnitsBusiness as decimal(10,2)) as [单位业务量能耗(度/erl)]";
                    break;
            }
        }
        else
        {
            switch (rblIndicators.SelectedValue)
            {
                case "1":
                    sItems = "SumPowers as [总电量(度)]";
                    break;
                case "2":
                    sItems = "cast(SumManagementRoom*100 as decimal(10,2)) as 管理用房耗电,cast(SumIntegratedRoom*100 as decimal(10,2))  as 综合机房耗电,cast(SumBusinessOffice*100 as decimal(10,2)) as 营业厅耗电,cast(SumBaseStation*100 as decimal(10,2)) as 基站耗电";
                    break;
                case "3":
                    sItems = "cast(SumUnitsBusiness as decimal(10,2)) as [单位业务量能耗(度/erl)]";
                    break;
            }
        }
        DataView mydv = bll.GetAnalysis(GetSearchString(), sItems);
        if (!String.IsNullOrEmpty(ViewState["sortExpression"].ToString()))
            mydv.Sort = ViewState["sortExpression"].ToString() + ViewState["sortDirection"].ToString();
        GridView1.DataSource = mydv;
        GridView1.DataBind();
        //-----------------------进行数据检查 给出未补空、空值等提示信息-----------------------------
        Text_Confirm_Upstate.Text = "";
        if (rblIndicators.SelectedIndex == 0 && tblType.SelectedIndex == 1 && !String.IsNullOrEmpty(sCheck) && !String.IsNullOrEmpty(sArea))
        {
            Text_Confirm_Upstate.Text = bll.GetNullInfoPowers(sCheck, sArea);
        }
        if (rblIndicators.SelectedIndex == 1 && tblType.SelectedIndex == 1 && !String.IsNullOrEmpty(sCheck) && !String.IsNullOrEmpty(sArea))
        {
            Text_Confirm_Upstate.Text = bll.GetNullInfo(sCheck, sArea);
        }
        if (rblIndicators.SelectedIndex == 2 && tblType.SelectedIndex == 1 && !String.IsNullOrEmpty(sCheck) && !String.IsNullOrEmpty(sArea))
        {
            Text_Confirm_Upstate.Text = bll.GetNullInfoService(sCheck, sArea);
        }
        if (Text_Confirm_Upstate.Text == "")
            Text_Confirm_Upstate.Visible = false;
        else
            Text_Confirm_Upstate.Visible = true;
        //-------------------------------------------------------------------------------------------
    }
    //--------------------------------------------------------------------------
    private string GetSearchString()
    {
        sArea = String.Empty;
        string searchStr = "(1=1)";
        for (int i = 0; i < lstArea.Items.Count; i++)
        {
            if (lstArea.Items[i].Selected == true)
            {
                sArea += sArea == String.Empty ? lstArea.Items[i].Value : "," + lstArea.Items[i].Value;
            }
        }
        if (slt.SelectedIndex == 2)
        {
            sArea += ddlArea.SelectedValue == String.Empty ? ddlArea.SelectedValue : "," + ddlArea.SelectedValue;
        }
        if (!String.IsNullOrEmpty(sArea))
            searchStr += " and Area_ID in (" + sArea + ")";
        else
            searchStr += " and Area_ID in (-1)";
        //获取所选择的年月
        //-----------------------2009.11.22 李伟修改 解决温度分析模块的迁移问题  START-------------------------//
        if (slt.Value != "divTmp")
        {
            sCheck = String.Empty;
            TreeNodeCollection checkedNodes = tvYears.CheckedNodes;
            foreach (TreeNode t in checkedNodes)
            {
                if (t.Text.Length == 6)
                    sCheck += sCheck == String.Empty ? t.Text : "," + t.Text;
            }
            if (!String.IsNullOrEmpty(sCheck))
            {
                searchStr += " and Years in (" + sCheck + ") ";
            }
        }
        else
        {
            searchStr += " and Years = '" + sCheck + "' ";
        }
        //-----------------------2009.11.22 李伟修改 解决温度分析模块的迁移问题  START-------------------------//
        return searchStr;
    }

    protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
    {
        if (e.Row.RowIndex != -1)
        {
            if (e.Row.Cells.Count == 6)
            {
                e.Row.Cells[2].Text = e.Row.Cells[2].Text + "%";
                e.Row.Cells[3].Text = e.Row.Cells[3].Text + "%";
                e.Row.Cells[4].Text = e.Row.Cells[4].Text + "%";
                e.Row.Cells[5].Text = e.Row.Cells[5].Text + "%";
            }
        }
    }
    protected void btnQuery_Click(object sender, EventArgs e)
    {
        //-----------------------2009.11.22 李伟修改 解决温度分析模块的迁移问题  START-------------------------//
        if (slt.Value != "divTmp")
        {
            if (String.IsNullOrEmpty(txtYears.Value))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请选择年月！');</script>");
                return;
            }
        }
        //-----------------------2009.11.22 李伟修改 解决温度分析模块的迁移问题  END-------------------------//
        if (txtYears.Value.Split(',').Length > 2 && tblType.SelectedIndex == 1)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('计算累积量只可选择某一个月份！');</script>");
            return;
        }
        this.BindGridViewData();
        GridView1.Visible = true;
        imgReport.Visible = false;
        cbShowData.Visible = false;
    }
    protected void btnReport_ServerClick(object sender, EventArgs e)
    {
        if (slt.Value != "divTmp")
        {
            if (String.IsNullOrEmpty(txtYears.Value))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请选择年月！');</script>");
                return;
            }
        }
        if (txtYears.Value.Split(',').Length > 2 && tblType.SelectedIndex == 1)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('计算累积量只可选择某一个月份！');</script>");
            return;
        }
        string sItems = String.Empty;
        //输出图表
        BarChart myBc = new BarChart();

        string tmp = String.Empty;
        if (tblType.SelectedValue == "1")
        {
            switch (rblIndicators.SelectedValue)
            {
                case "1":
                    sItems = "Powers as 总电量";
                    break;
                case "2":
                    sItems = "cast(ManagementRoom as decimal(10,2)) as 管理用房耗电,cast(IntegratedRoom as decimal(10,2)) as 综合机房耗电,cast(BusinessOffice as decimal(10,2)) as 营业厅耗电,cast(BaseStation as decimal(10,2)) as 基站耗电";
                    break;
                case "3":
                    sItems = "cast(UnitsBusiness as decimal(10,2)) as 单位业务量能耗";
                    break;
            }
        }
        else
        {
            switch (rblIndicators.SelectedValue)
            {
                case "1":
                    sItems = "SumPowers as 总电量";
                    break;
                case "2":
                    sItems = "cast(SumManagementRoom as decimal(10,2)) as 管理用房耗电,cast(SumIntegratedRoom as decimal(10,2))  as 综合机房耗电,cast(SumBusinessOffice as decimal(10,2)) as 营业厅耗电,cast(SumBaseStation as decimal(10,2)) as 基站耗电";
                    break;
                case "3":
                    sItems = "cast(SumUnitsBusiness as decimal(10,2)) as 单位业务量能耗";
                    break;
            }
        }
        DataTable dt = bll.GetAnalysis(GetSearchString(), sItems).Table;
        string imgUrl = Server.MapPath("Graphic\\Graphic") + (string)Session["Baimasoft_Pers_ID"] + ".jpg";
        string sTitle = String.Empty;
        switch (rblIndicators.SelectedValue)
        {
            case "1":
                sTitle = "总电量";
                break;
            case "2":
                sTitle = "分项电量对比";
                break;
            case "3":
                sTitle = "单位业务量能耗";
                break;
        }
        if (dt.Rows.Count > 0)
        {
            switch (brlType.SelectedValue.ToString())
            {
                case "1":
                    //执行同月图表
                    if (sCheck.Split(',').Length > 1)
                    {
                        ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('生成同月图表，请选择某个月份！');</script>");
                        return;
                    }
                    tmp = dt.Rows[0]["年月"].ToString();
                    try
                    {
                        tmp = tmp.Substring(0, 4) + "年" + tmp.Replace(tmp.Substring(0, 4), "") + "月";
                    }
                    catch
                    {

                    }
                    myBc.ChartTitle = tmp + "月份不同地区" + sTitle + "图表";
                    myBc.ChartXTitle = "地区";
                    myBc.ChartYTitle = "电量";
                    myBc.TextValue = "地区";
                    myBc.DataSource = dt;
                    if (brlGraphic.SelectedValue == "1")
                    {
                        Bitmap img = myBc.DrawBarChart();
                        img.Save(imgUrl, ImageFormat.Jpeg);
                    }
                    else
                    {
                        if (dt.Rows.Count <= 1)
                        {
                            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('生成折线图至少需要两条以上的记录数，请更改查询条件！');</script>");
                            return;
                        }
                        Bitmap img = myBc.DrawBrokenLine();
                        img.Save(imgUrl, ImageFormat.Jpeg);
                    }
                    break;
                case "2":
                    //执行同区图表
                    if (sArea.Split(',').Length > 1)
                    {
                        ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('生成同区图表，请选择相同区域！');</script>");
                        return;
                    }
                    tmp = dt.Rows[0]["地区"].ToString();
                    myBc.ChartTitle = tmp + "不同月份" + sTitle + "图表";
                    myBc.ChartXTitle = "月份";
                    myBc.ChartYTitle = "电量";
                    myBc.TextValue = "年月";
                    myBc.DataSource = dt;
                    if (brlGraphic.SelectedValue == "1")
                    {
                        Bitmap img = myBc.DrawBarChart();
                        img.Save(imgUrl, ImageFormat.Jpeg);
                    }
                    else
                    {
                        if (dt.Rows.Count <= 1)
                        {
                            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('生成折线图至少需要两条以上的记录数，请更改查询条件！');</script>");
                            return;
                        }
                        Bitmap img = myBc.DrawBrokenLine();
                        img.Save(imgUrl, ImageFormat.Jpeg);
                    }
                    break;
            }
            GridView1.Visible = false;
            imgReport.Visible = true;
            cbShowData.Visible = true;
            cbShowData.Checked = false;
            Random rnd = new Random();
            imgReport.ImageUrl = "Graphic\\Graphic" + (string)Session["Baimasoft_Pers_ID"] + ".jpg?" + DateTime.Now.Millisecond + "&" + rnd.Next(100).ToString();
        }
        else
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('没有数据用于生成图表，请重新选择范围！');</script>");
        }
    }
    protected void ddlLargeArea_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (!String.IsNullOrEmpty(ddlLargeArea.SelectedValue))
        {
            lstArea.DataSource = bll.GetAreaByLargeArea(ddlLargeArea.SelectedValue);
            lstArea.DataTextField = "Name";
            lstArea.DataValueField = "ID";
            lstArea.DataBind();
        }
        else
        {
            lstArea.Items.Clear();
        }
        txtArea.Value = String.Empty;
    }
    protected void ddlEquipment1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (!String.IsNullOrEmpty(ddlEquipment1.SelectedValue))
        {
            lstArea.DataSource = bll.GetAreaByEquipment("1", ddlEquipment1.SelectedValue);
            lstArea.DataTextField = "Name";
            lstArea.DataValueField = "ID";
            lstArea.DataBind();
        }
        else
        {
            lstArea.Items.Clear();
        }
        txtArea.Value = String.Empty;
    }
    protected void ddlEquipment2_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (!String.IsNullOrEmpty(ddlEquipment2.SelectedValue))
        {
            lstArea.DataSource = bll.GetAreaByEquipment("2", ddlEquipment2.SelectedValue);
            lstArea.DataTextField = "Name";
            lstArea.DataValueField = "ID";
            lstArea.DataBind();
        }
        else
        {
            lstArea.Items.Clear();
        }
        txtArea.Value = String.Empty;
    }
    protected void ddlEquipment3_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (!String.IsNullOrEmpty(ddlEquipment3.SelectedValue))
        {
            lstArea.DataSource = bll.GetAreaByEquipment("3", ddlEquipment3.SelectedValue);
            lstArea.DataTextField = "Name";
            lstArea.DataValueField = "ID";
            lstArea.DataBind();
        }
        else
        {
            lstArea.Items.Clear();
        }
        txtArea.Value = String.Empty;
    }
    protected void ddlArea_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (!String.IsNullOrEmpty(ddlArea.SelectedValue))
        {
            lstArea.DataSource = bll.GetAreaByNeighbors(ddlArea.SelectedValue);
            lstArea.DataTextField = "Name";
            lstArea.DataValueField = "ID";
            lstArea.DataBind();
        }
        else
        {
            lstArea.Items.Clear();
        }
        txtArea.Value = String.Empty;
    }
    protected void btn_Click(object sender, EventArgs e)
    {
        lstArea.Items.Clear();
        this.BindlstArea();
        txtArea.Value = String.Empty;
        txtlst.Value = "";
    }
    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (ViewState["sortDirection"].ToString() == " ASC")
        {
            ViewState["sortDirection"] = " DESC";
        }
        else
        {
            ViewState["sortDirection"] = " ASC";
        }
        ViewState["sortExpression"] = e.SortExpression;
        this.BindGridViewData();
    }
    protected void cbShowData_CheckedChanged(object sender, EventArgs e)
    {
        if (cbShowData.Checked)
        {
            GridView1.Visible = true;
            this.BindGridViewData();
        }
        else
        {
            GridView1.Visible = false;
        }
    }
    protected void btnArea_Click(object sender, EventArgs e)
    {
        lstArea.DataSource = bll.GetAreaByTemp(txtMin.Text.Trim(), txtMax.Text.Trim(), ddlYears.SelectedValue.Trim());
        lstArea.DataTextField = "Name";
        lstArea.DataValueField = "ID";
        lstArea.DataBind();
    }
}
